<template>
  <div>
    <MyHeader title="地址列表" :arrow="true" text="返回"/>
    <van-address-list :list="addressList" v-model="defaultChoose" @add="$router.push('address/edit')" @edit="delAddress" @select="selectAddress" :switchable="isOrder">
      <h3 v-if="addressList.length===0">暂无地址</h3>
    </van-address-list>
  </div>
</template>

<script>
import MyHeader from '@/components/MyHeader'
const addressList = [
  {
    id: 1,
    name: '山老板',
    tel: '18888888888',
    address: '江苏省南京市总统府',
    isDefault: true
  }, {
    id: 2,
    name: '张三丰',
    tel: '19999999999',
    address: '江苏省南京市江宁区江苏软件园',
    isDefault: false
  }
]
export default {
  name: 'AddressList',
  components: { MyHeader },
  data () {
    return {
      addressList: [...addressList],
      defaultChoose: 1,
      isOrder: false
    }
  },
  methods: {
    getAddressList () {
      this.$axios.get(`/v1/users/${this.$cookies.get('user_id')}/addresses`)
        .then(({ data }) => {
          if (data.code === 20000) {
            this.addressList = data.data.map(item => {
              if (item.is_user_default) {
                this.defaultChoose = item.id
              }
              return {
                id: item.id,
                name: item.name,
                tel: item.phone,
                address: item.address + ' ' + item.address_detail,
                isDefault: item.is_user_default
              }
            }).reverse()
          }
        })
    },
    delAddress (item) {
      this.$dialog.confirm({ message: '确定删除该地址吗' }).then(() => {
        this.$axios.post(`/v1/users/${this.$cookies.get('user_id')}/addresses/${item.id}`).then(({ data }) => {
          if (data.code === 20000) {
            this.$notify({
              message: data.data,
              type: 'success',
              onClose: () => {
                this.getAddressList()
              }
            })
          }
        })
      }).catch(() => {})
    },
    selectAddress (item, index) {
      this.$router.replace({ name: 'OrderDetail', params: { index } })
    }
  },
  created () {
    this.$nextTick(() => {
      this.getAddressList()
      this.isOrder = this.$route.query.isOrder === 'true'
    })
  }
}
</script>

<style scoped>

</style>
